package com.tgy.JUC.CollectionUnSafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/***
 * @ClassName: HashSetUnsafe
 * @Description: HashSet 不安全测试
 * @Auther: 送你一块二向箔
 * @Date: 14:07 2022/3/11
 * @version : V1.0
 */
public class HashSetUnsafe {
    public static void main(String[] args) {
        //unsafe();
        //safeSync();
        safeCopyOnWrite();
    }

    public static void safeCopyOnWrite(){
        CopyOnWriteArraySet<String> strings = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
    }


    public static void safeSync(){
        Set<String> strings = Collections.synchronizedSet(new HashSet<>());
        //HashSet<String> strings = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
    }
    public static void unsafe(){
        // Set<String> strings = Collections.synchronizedSet(new HashSet<>());
        HashSet<String> strings = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(strings);
            }).start();
        }
    }



}
